package topic

import (
	"community-service/cmd/api/internal/models/model"
	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
)

type ListTopicLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewListTopicLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListTopicLogic {
	return &ListTopicLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListTopicLogic) ListTopic(req *types.TopicReq) (*types.TopicList, error) {
	var resp types.TopicList
	topicQuery := l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityTopic{})

	// 按名称模糊搜索
	if req.Name != "" {
		topicQuery = topicQuery.Where("name LIKE ?", "%"+req.Name+"%")
	}

	// 按专栏筛选
	if req.MenuId != 0 {
		topicQuery = topicQuery.Where("menu_id = ?", req.MenuId)
	}

	if req.Type != types.TopicTypeAll {
		topicQuery.Where("type = ?", req.Type)
	}

	// 查询总数
	if err := topicQuery.Count(&resp.Total).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	// 查询数据
	if err := topicQuery.
		Joins("topic").
		Joins(fmt.Sprintf("LEFT JOIN %s post ON post.topic_id = topic.id", model.TableNameCsCommunityPost)).
		Select("topic.*", "COUNT(post.id) post_count", "IFNULL(SUM(post.view_count), 0) view_count").
		Group("topic.id").
		Order("topic.id ASC").
		Offset((req.PageNum - 1) * req.PageSize).Limit(req.PageSize).Find(&resp.Data).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	return &resp, nil
}
